class Emitter {
  constructor() {
    this.events = new Map();
  }

  on(type, handler) {
    if (!this.events.has(type)) {
      this.events.set(type, []);
    }
    this.events.get(type).push(handler);
    return this; // 返回自身以支持链式调用
  }

  off(type, handler) {
    const handlers = this.events.get(type);
    if (!handlers) return;
    if (!handler) {
      this.events.delete(type);
      return;
    }
    const index = handlers.indexOf(handler);
    if (index !== -1) {
      handlers.splice(index, 1);
    }
  }

  emit(type, data) {
    const handlers = this.events.get(type);
    if (handlers) {
      handlers.forEach((handler) => handler(data));
    }
  }
}
